import fs from 'fs'
import {fileURLToPath,pathToFileURL} from 'url'


function findControllers(){
    let xDir = new URL('../controllers',import.meta.url);//使用es6的模板路径
    let controllerDir=fileURLToPath(xDir);

    if(fs.existsSync(controllerDir)){
        let allFiles = fs.readdirSync(controllerDir);//同步方法
        let allControllersFiles = allFiles.filter(item=>item.endsWith('.js'))
            .map(item=>pathToFileURL(controllerDir+'/'+item));


        return allControllersFiles;
    }
    return null;
}


function registerRoute(router,controllers){
    if(controllers === null){
        return
    }

    //遍历所有的控制器文件，动态导入每一个 控制器模块
    controllers.forEach(async item=>{
        //动态导入
        let {obj}=await import(item);


        //遍历模块中的对象
        for (let key in obj){
            let [keyMethod,keyPath] = key.split(' ');
            let keyFn = obj[key];

            if(keyMethod === 'get'){
                router.get(keyPath,keyFn);
            }
            if(keyMethod === 'post'){
                router.post(keyPath,keyFn);
            }
            if(keyMethod === 'put'){
                router.put(keyPath,keyFn);
            }
            if(keyMethod === 'delete'){
                router.delete(keyPath,keyFn);
            }
        }
    })
}

export const findAllControllers = findControllers

export const regRoute =registerRoute


